package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("AdditiveRestController")
public class AdditiveRestController extends CmiEmaController {

	/**
	 * Create a new Additive entity
	 * 
	 */
	@RequestMapping(value = "/newAdditive", method = RequestMethod.POST)
	@ResponseBody
	public Object newAdditive(@RequestBody Additive additive) {
		additiveService.saveAdditive(additive);
		return JSONObject.parse(cmiPsonService.toJsonString(additiveDAO.findAdditiveByPrimaryKey(additive.getId()), 2));
	}

	@RequestMapping(value = "/restNewAdditive", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewAdditive(@RequestBody String additiveJson) {
		Additive additive = new Gson().fromJson(additiveJson, Additive.class);
		appendReferences(additive);
		additiveService.saveAdditive(additive);
		return JSONObject.parse(cmiPsonService.toJsonString(additiveDAO.findAdditiveByPrimaryKey(additive.getId()), 2));
	}

	@RequestMapping(value = "/saveAdditive", method = RequestMethod.PUT)
	@ResponseBody
	public Additive saveAdditive(@RequestBody Additive additive) {
		additiveService.saveAdditive(additive);
		return additiveDAO.findAdditiveByPrimaryKey(additive.getId());
	}

	@RequestMapping(value = "/restSaveAdditive", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveAdditive(@RequestBody String additiveJson) {
		Additive additive = new Gson().fromJson(additiveJson, Additive.class);
		appendReferences(additive);
		CmiPsonService cmiPsonService = new CmiPsonService();
		additiveService.saveAdditive(additive);
		return JSONObject.parse(cmiPsonService.toJsonString(additiveDAO.findAdditiveByPrimaryKey(additive.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteAdditive/{additiveId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteAdditive(@PathVariable Integer additiveId) {
		Additive additive = additiveDAO.findAdditiveByPrimaryKey(additiveId);
		additiveService.deleteAdditive(additive);
	}

	@RequestMapping(value = "/restConfirmDeleteAdditives")
	@ResponseBody
	public Object restConfirmDeleteAdditives(@RequestBody Set<Integer> deleteAdditivesIds) {
		Set<Additive> deleteAdditives = additiveDAO.findAdditivesByIds(deleteAdditivesIds);
		Set<Additive> referencedAdditives = additiveService.loadReferenceAdditives(deleteAdditives);
		deleteAdditives.removeAll(referencedAdditives);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedAdditives);
		jsonObject.put("deleteEntitys", deleteAdditives);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteAdditives")
	@ResponseBody
	public Object restDeleteAdditives(@RequestBody Set<Additive> deleteAdditives) {
		Iterator<Additive> iterator = deleteAdditives.iterator();
		while (iterator.hasNext()) {
			Additive currentAdditive = iterator.next();
			additiveService.deleteAdditive(currentAdditive);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listAdditives");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadAdditive/{additiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAdditive(@PathVariable Integer additiveId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(additiveDAO.findAdditiveByPrimaryKey(additiveId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadAdditiveAdditiveaddresss/{additiveId}/additiveaddresss/{relatedadditiveaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAdditiveAdditiveaddresss(@PathVariable Integer additiveId,
			@PathVariable Integer relatedadditiveaddressId, @RequestBody CmiPagination cmiPagination) {
		Additiveaddress additiveaddress = additiveaddressDAO.findAdditiveaddressByPrimaryKey(relatedadditiveaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(additiveaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadAdditiveFoodadditives/{additiveId}/foodadditives/{relatedfoodadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAdditiveFoodadditives(@PathVariable Integer additiveId,
			@PathVariable Integer relatedfoodadditiveId, @RequestBody CmiPagination cmiPagination) {
		Foodadditive foodadditive = foodadditiveDAO.findFoodadditiveByPrimaryKey(relatedfoodadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadAdditiveFoodbatchadditives/{additiveId}/foodbatchadditives/{relatedfoodbatchadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAdditiveFoodbatchadditives(@PathVariable Integer additiveId,
			@PathVariable Integer relatedfoodbatchadditiveId, @RequestBody CmiPagination cmiPagination) {
		Foodbatchadditive foodbatchadditive = foodbatchadditiveDAO
				.findFoodbatchadditiveByPrimaryKey(relatedfoodbatchadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatchadditive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadAdditivePurchaseadditives/{additiveId}/purchaseadditives/{relatedpurchaseadditiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadAdditivePurchaseadditives(@PathVariable Integer additiveId,
			@PathVariable Integer relatedpurchaseadditiveId, @RequestBody CmiPagination cmiPagination) {
		Purchaseadditive purchaseadditive = purchaseadditiveDAO
				.findPurchaseadditiveByPrimaryKey(relatedpurchaseadditiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchaseadditive, 2, cmiPagination));
	}

	public void appendReferences(Additive additive) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Additiveaddress> additiveaddresssForAdditive = new HashSet<>();
		for (Additiveaddress additiveaddress_Additive : additive.getAdditiveaddresssForAdditive()) {
			additiveaddresssForAdditive
					.add(additiveaddressService.findAdditiveaddressByPrimaryKey(additiveaddress_Additive.getId()));
		}
		additive.setAdditiveaddresssForAdditive(additiveaddresssForAdditive);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodadditive> foodadditivesForAdditive = new HashSet<>();
		for (Foodadditive foodadditive_Additive : additive.getFoodadditivesForAdditive()) {
			foodadditivesForAdditive
					.add(foodadditiveService.findFoodadditiveByPrimaryKey(foodadditive_Additive.getId()));
		}
		additive.setFoodadditivesForAdditive(foodadditivesForAdditive);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatchadditive> foodbatchadditivesForAdditive = new HashSet<>();
		for (Foodbatchadditive foodbatchadditive_Additive : additive.getFoodbatchadditivesForAdditive()) {
			foodbatchadditivesForAdditive.add(
					foodbatchadditiveService.findFoodbatchadditiveByPrimaryKey(foodbatchadditive_Additive.getId()));
		}
		additive.setFoodbatchadditivesForAdditive(foodbatchadditivesForAdditive);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchaseadditive> purchaseadditivesForAdditive = new HashSet<>();
		for (Purchaseadditive purchaseadditive_Additive : additive.getPurchaseadditivesForAdditive()) {
			purchaseadditivesForAdditive
					.add(purchaseadditiveService.findPurchaseadditiveByPrimaryKey(purchaseadditive_Additive.getId()));
		}
		additive.setPurchaseadditivesForAdditive(purchaseadditivesForAdditive);
	}

	@RequestMapping(value = "/restGetAdditiveAdditiveaddresss/{additiveId}/additiveaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetAdditiveAdditiveaddresss(@PathVariable Integer additiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				additiveDAO.findAdditiveByPrimaryKey(additiveId).getAdditiveaddresssForAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetAdditiveFoodadditives/{additiveId}/foodadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetAdditiveFoodadditives(@PathVariable Integer additiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				additiveDAO.findAdditiveByPrimaryKey(additiveId).getFoodadditivesForAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetAdditiveFoodbatchadditives/{additiveId}/foodbatchadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetAdditiveFoodbatchadditives(@PathVariable Integer additiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				additiveDAO.findAdditiveByPrimaryKey(additiveId).getFoodbatchadditivesForAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetAdditivePurchaseadditives/{additiveId}/purchaseadditives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetAdditivePurchaseadditives(@PathVariable Integer additiveId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				additiveDAO.findAdditiveByPrimaryKey(additiveId).getPurchaseadditivesForAdditive(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListAdditives", method = RequestMethod.GET)
	@ResponseBody
	public Object restListAdditives() {
		return JSONObject.parse(cmiPsonService.toJsonString(additiveService.loadAdditives(), 2));
	}

	@RequestMapping(value = "/restListAdditivesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListAdditivesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = additivePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Additive> additives = additiveDAO.findAllAdditives(startResult, cmiPagination.getPaginationSize());
		String additiveString = cmiPsonService.toPsonString(additives, 2, cmiPagination);

		return JSONObject.parse(additiveString);
	}

	@RequestMapping("/additiveSelectBox")
	@ResponseBody
	public JSONObject additiveSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressService.loadAdditiveaddresssByIdSet(searchValue);
				break;
			case "Foodadditive":
				entitySet = foodadditiveService.loadFoodadditivesByIdSet(searchValue);
				break;
			case "Foodbatchadditive":
				entitySet = foodbatchadditiveService.loadFoodbatchadditivesByIdSet(searchValue);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveService.loadPurchaseadditivesByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressDAO.findAllAdditiveaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = additiveaddressService.countAdditiveaddresss();
				break;
			case "Foodadditive":
				entitySet = foodadditiveDAO.findAllFoodadditives((pageNumber - 1) * paginationSize, paginationSize);
				count = foodadditiveService.countFoodadditives();
				break;
			case "Foodbatchadditive":
				entitySet = foodbatchadditiveDAO.findAllFoodbatchadditives((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchadditiveService.countFoodbatchadditives();
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findAllPurchaseadditives((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchaseadditiveService.countPurchaseadditives();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Additiveaddress":
				entitySet = additiveaddressDAO.findAdditiveaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = additiveaddressService.countAdditiveaddresssByName(queryword);
				break;
			case "Foodadditive":
				entitySet = foodadditiveDAO.findFoodadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodadditiveService.countFoodadditivesByName(queryword);
				break;
			case "Foodbatchadditive":
				entitySet = foodbatchadditiveDAO.findFoodbatchadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchadditiveService.countFoodbatchadditivesByName(queryword);
				break;
			case "Purchaseadditive":
				entitySet = purchaseadditiveDAO.findPurchaseadditiveByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchaseadditiveService.countPurchaseadditivesByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
